<template>
	<div class="picking zy-content">
		<div class="searchBox search-box-layout">
			<Row :gutter="24">
				<Col span="6">
					<div style="width: 100%">
						<p class="label">{{ $t('安装位置') }}</p>
						<div class="ipt">
							<Cascader :data="orgList" :transfer="true" v-model="orgCodeList" change-on-select @on-change="handleCasChange" />
						</div>
					</div>
				</Col>
				<Col span="6">
					<div>
						<p class="label">{{ $t('equipCheck.SerialNo') }}</p>
						<div class="ipt">
							<Select
								v-model="searchParams.deviceMId"
								filterable
								clearable
								:placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`"
								:remote-method="handleRemote"
							>
								<Option v-for="item in deviceMIdList" :value="item.deviceMId" :label="item.desc" :key="item.deviceMId" />
							</Select>
						</div>
					</div>
				</Col>

				<Col span="4">
					<div>
						<p class="label">{{ $t('点检级别') }}</p>
						<div class="ipt">
							<Select v-model="searchParams.planLevel" clearable :placeholder="`${$t('common.selectInfo')}`">
								<Option v-for="item of levelList" :value="item.name" :key="item.key" :label="item.name"> </Option>
							</Select>
						</div>
					</div>
				</Col>
				<template v-if="dayStatus === '年'">
					<Col span="4">
						<div>
							<p class="label">{{ $t('年') }}</p>
							<div class="ipt">
								<DatePicker type="year" v-model="searchParams.year" :placeholder="`${$t('common.selectInfo')}`" />
							</div>
						</div>
					</Col>
				</template>

				<template v-else>
					<Col span="4">
						<div>
							<p class="label">{{ $t('日') }}</p>
							<div class="ipt">
								<DatePicker type="datetimerange" v-model="dayArr" format="yyyy-MM-dd" :placeholder="`${$t('common.selectInfo')}`" />
							</div>
						</div>
					</Col>
				</template>

				<Col span="2">
					<div>
						<p class="label">{{ $t('状态') }}</p>
						<div class="ipt">
							<Select v-model="dayStatus" @on-change="dayChange">
								<Option v-for="item in dayList" :value="item.value" :key="item.value">{{ item.label }}</Option>
							</Select>
						</div>
					</div>
				</Col>
				<Col span="24" class="t-c">
					<div>
						<p class="label hide-label">--</p>
						<div class="ipt">
							<Button class="search-btn" type="primary" @click="getDatalist">{{ $t('common.Query') }} </Button>
							<!-- <Button
                class="search-btn"
                @click="exportTemplateClick(searchParams)"
                >{{ $t("导出") }}
              </Button> -->
							<Button class="reset-btn" @click="reset()">{{ $t('common.reset') }} </Button>
						</div>
					</div>
				</Col>
			</Row>
		</div>
		<div class="list-layout mt16">
			<div class="btns clear">
				<span class="title">{{ $t('点检计划看板') }}</span>
			</div>
			<template v-if="showStatus">
				<div style="display: flex; justify-content: center; align-items: center">
					<span>暂无数据</span>
				</div>
			</template>
			<template v-else>
				<div class="tableContent" style="overflow-x: scroll; overflow-y: auto">
					<table class="table table-bordered text-nowrap">
						<thead>
							<tr>
								<th class="text-center">{{ $t('设备编号') }}</th>
								<th class="text-center">{{ $t('设备名称') }}</th>
								<th class="text-center">{{ $t('设备流水号') }}</th>
								<th class="text-center">{{ $t('点检级别') }}</th>
								<th class="text-center">{{ $t('点检周期') }}</th>
								<th v-for="year in yearList" class="text-center" :colspan="year.colspan" :key="year">
									{{ year.name }}
								</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td class="text-center" />
								<td class="text-center" />
								<td class="text-center" />
								<td class="text-center" />
								<td class="text-center">{{ !dayChecked ? 'WEEK' : 'DAY' }}</td>
								<template v-for="(item, i) in cardDetail">
									<template v-if="!dayChecked">
										<td class="text-center" :key="item">{{ i + 1 }}</td>
									</template>
									<template v-else>
										<td class="text-center" :key="item">
											{{ item.start !== '' ? $moment(item.start).format('DD') : '' }}
										</td>
									</template>
								</template>
							</tr>
							<tr v-for="item in cardList" :key="item">
								<td class="text-center">{{ item.deviceNo }}</td>
								<td class="text-center">{{ item.deviceName }}</td>
								<td class="text-center">{{ item.deviceMId }}</td>
								<td class="text-center">{{ item.planLevel }}</td>
								<td class="text-center">{{ item.cycleUnit }}</td>
								<template v-for="(list, index) in item.yearOfWeeks">
									<td class="text-center" :key="index" v-if="Number(list.column) === 2">
										<span>⃞</span>
									</td>
									<td class="text-center" :key="index" v-if="Number(list.column) === 1">
										<span style="color: #ff0000">☒</span>
									</td>
									<td class="text-center" :key="index" v-if="Number(list.column) === 0">
										<span style="color: #00ff00">☑</span>
									</td>
									<td
                    class="text-center"
                    :key="index"
                    v-if="Number(list.column) === 3"
                  />
								</template>
							</tr>
						</tbody>
					</table>
				</div>
			</template>
			<div class="pageWrap mt16">
				<pageLeftTitle :total="total" />
				<Page
					:total="total"
					:page-size="pageSize"
					:page-size-opts="$variable.pageSizes"
					:current="pageNum"
					@on-change="changePageNum"
					@on-page-size-change="changePageSize"
					show-sizer
					show-total
				/>
			</div>
		</div>
	</div>
</template>

<script>
import fileDownload from 'js-file-download';
import recursion from '@/util/recursion';
export default {
	name: 'project',
	data() {
		return {
			dayNum: [],
			dayArr: [],
			cardDetail: [],
			yearList: ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'],
			cardList: [],
			dayChecked: false,
			dayStatus: '年',
			dayList: [
				{
					value: '年',
					label: '年',
				},
				{
					value: '日',
					label: '日',
				},
			],
			importExcelState: false,
			deviceMIdList: [],
			deviceNameList: [],
			orgList: [],
			levelList: [
				{ name: '一级点检', key: 1 },
				{ name: '二级点检', key: 2 },
				{ name: '三级点检', key: 3 },
			],
			orgCodeList: [],
			status: 0,
			confirmId: '',
			delId: '',
			searchParams: {
				year: this.$moment(new Date()).format('YYYY'),
				orgCodes: [],
			},
			checkBtnPermission: {},
			total: 0,
			pageSize: 20,
			pageNum: 1,
			pageSizeOption: [10, 20, 30, 40],
			importVisible: false,
			showStatus: false,
			allCheck: false,
			create: false,
			confirmBatchFaultCodeShowF: false,
			confirmBatchLoading: false,
			confirmFaultCodeShowF: false,
			confirmLoading: false,
			delLoading: false,
			delBatchFaultCodeShowF: false,
			delBatchLoading: false,
			columns: [
				{
					type: 'selection',
					align: 'center',
					width: 60,
				},
				{
					title: `${this.$t('设备等级')}`,
					key: 'categoryName',
					minWidth: 80,
					align: 'center',
				},
				{
					title: `${this.$t('设备类别')}`,
					key: 'deviceType',
					minWidth: 180,
					align: 'center',
				},
				{
					title: `${this.$t('maintenance.EquipmentNo')}`,
					key: 'deviceNo',
					align: 'center',
					minWidth: 100,
				},
				{
					title: `${this.$t('设备名称')}`,
					key: 'deviceName',
					align: 'center',
					minWidth: 100,
				},
				{
					title: `${this.$t('设备流水号')}`,
					key: 'deviceMId',
					minWidth: 130,
					align: 'center',
				},
				{
					title: `${this.$t('maintenance.MaintenanceType')}`,
					key: 'classifyName',
					minWidth: 120,
					align: 'center',
				},
				{
					title: `${this.$t('点检周期')}`,
					key: 'triggerCycleName',
					minWidth: 160,
					align: 'center',
				},
				{
					title: `${this.$t('点检级别')}`,
					key: 'planLevelName',
					minWidth: 160,
					align: 'center',
				},
				{
					title: `${this.$t('点检项目')}`,
					key: 'itemProject',
					width: 200,
					align: 'center',
					tooltip: true,
				},
				{
					title: `${this.$t('点检方式')}`,
					key: 'itemMethod',
					width: 200,
					align: 'center',
					tooltip: true,
				},
				{
					title: `${this.$t('点检标准')}`,
					key: 'unitName',
					minWidth: 200,
					align: 'center',
				},
				// {
				//     title: `${this.$t('maintenance.UpperLimit')}`,
				//     key: "maxValue",
				//     minWidth: 100,
				//     align: "center"
				// },
				{
					title: `${this.$t('需求人数')}`,
					key: 'minValue',
					minWidth: 140,
					align: 'center',
				},
				// { title: "标准工时(min)", key: "itemHours", minWidth: 120,align: "center" },
				{
					title: `${this.$t('创建人')}`,
					key: 'createName',
					minWidth: 120,
					align: 'center',
				},
				{
					title: `${this.$t('是否上传sop')}`,
					key: 'sopTag',
					align: 'center',
					minWidth: 130,
					render: (h, params) => {
						if (Number(params.row.sopTag) >= 0) {
							return h('div', [h('span', this.sopTagList.find((val) => val.key == params.row.sopTag).name)]);
						} else {
							return h('div', [h('span', '')]);
						}
					},
				},
				{
					title: `${this.$t('安装位置')}`,
					key: 'position4',
					align: 'center',
					minWidth: 160,
					tooltip: true,
				},
				{
					title: `${this.$t('创建时间')}`,
					key: 'createTime',
					minWidth: 200,
					align: 'center',
				},
				// { title: "确认人", key: "verifyName", minWidth: 200,align: "center" },
				// { title: "确认时间", key: "verifyTime", minWidth: 200,align: "center" },
				{
					title: `${this.$t('common.operation')}`,
					slot: 'action',
					fixed: 'right',
					minWidth: 240,
					align: 'center',
				},
			],
			deviceTypeList: [],
			data: [],
		};
	},
	created() {
		this.getFaultCategory('设备类型');
	},
	mounted() {
		this.getOrgList();
		this.getDatalist();
	},
	methods: {
		reset() {
			this.pageNum = 1;
			this.dayStatus = '年';
			this.$refs.cascaderComp.value = [];
			this.orgCodeList = [];
			this.searchParams.year = this.$moment();
			this.dayArr = [];
			this.getDatalist();
		},
		dayChange(val) {
			if (val === '日') {
				this.searchParams.year = '';
			} else {
				this.searchParams.year = this.$moment();
				this.dayArr = [];
			}
		},
		exportTemplateClick({ orgCode, deviceMId }) {
			let filName = '年历看板';
			const params = {
				deviceMId,
				installPositionName: this.searchParams.orgCode ? JSON.stringify(this.searchParams.orgCode) : '',
			};
			if (this.dayStatus == '日') {
				filName = '日历看板';
				params.startDate = this.dayArr && this.dayArr.length ? this.$moment(this.dayArr[0]).format('YYYY-MM-DD') : undefined;
				params.endDate = this.dayArr && this.dayArr.length ? this.$moment(this.dayArr[1]).format('YYYY-MM-DD') : undefined;
			} else {
				params.year = this.searchParams.year ? this.$moment(this.searchParams.year).format('YYYY') : undefined;
			}
			this.axios({
				method: 'get',
				url: '/dms/calendar/board/planMaintenanceExport',
				responseType: 'blob',
				params,
			}).then((res) => {
				fileDownload(res, filName + '.xlsx');
			});
		},
		getDatalist() {
			this.showStatus = false;
			// let yearList = [
			//   "Jan.",
			//   "Feb.",
			//   "Mar.",
			//   "Apr.",
			//   "May.",
			//   "Jun.",
			//   "Jul.",
			//   "Aug.",
			//   "Sep.",
			//   "Oct.",
			//   "Nov.",
			//   "Dec.",
			// ];
      const params={
        ...this.searchParams,
					year: this.searchParams.year ? this.$moment(this.searchParams.year).format('YYYY') : undefined,
					startDate: this.dayArr && this.dayArr.length ? this.$moment(this.dayArr[0]).format('YYYY-MM-DD') : undefined,
					endDate: this.dayArr && this.dayArr.length ? this.$moment(this.dayArr[1]).format('YYYY-MM-DD') : undefined,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					installPositionName: this.searchParams.orgCode ? JSON.stringify(this.searchParams.orgCode) : '',
      }
      delete params.orgCodes
      delete params.orgCode
			let yearList = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
			this.axios({
				method: 'post',
				url: '/dms/devSpotCheckPlan/getDevSpotCheckPlanListByTime',
				params,
			}).then((res) => {
				// const res = this.res;
				this.total = res.data.total || 0;
				if (res.data.records && res.data.records.length) {
					this.yearList = yearList.map((val) => ({
						name: val,
						colspan: '',
					}));
					this.cardList = res.data.records;
					this.cardDetail = res.data.records[0].yearOfWeeks;
					this.yearList.forEach((item, i) => {
						item['colspan'] = this.cardDetail.filter((list) => Number(list.month) === i + 1).length;
					});
					if (this.dayStatus === '年') {
						this.dayChecked = false;
					} else {
						this.dayChecked = true;
						this.cardList.forEach((obj) => {
							let newDetails = [];
							for (let m = 1; m <= this.yearList.length; m++) {
                const fdMonthList = obj.yearOfWeeks.filter((i) => i.month === m);
                const itemObj={
										end: '',
										month: m,
										start: '',
										column: 3,
										weekIndex: '',
									}
								// if (fdMonthList.length) {
								// 	newDetails = newDetails.concat(fdMonthList);
								// } else {
								// 	newDetails.push({
								// 		end: '',
								// 		month: '',
								// 		start: '',
								// 		column: 9,
								// 		weekIndex: '',
								// 	});
								// }
                if (fdMonthList.length) {
									newDetails = newDetails.concat(fdMonthList);
								} else {
									newDetails.push(itemObj);
								}
							}
							obj.yearOfWeeks = newDetails;
						});
						this.cardDetail = this.cardList[0].yearOfWeeks;
					}
				} else {
					this.showStatus = true;
				}
			});
		},
		// 基础数据
		//车间
		getOrgList() {
			this.axios({
				method: 'get',
				url: '/basic/organization/findListByToken',
				params: {
					level: 0,
				},
			}).then((res) => {
				if (res.code === 200) {
					const obj = {
						label: 'name',
						value: 'code',
						children: 'children',
					};
					this.orgList = recursion.convertTree(res.data, obj);
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		debounceSerach(fn, delay) {
			let _this = this;
			return function f(...args) {
				if (_this.timeID) {
					clearTimeout(_this.timeID);
				}
				_this.timeID = setTimeout(() => {
					fn(args);
				}, delay);
			};
		},
		handleRemote(query) {
			if (!query) {
				return;
			}
			const fn = this.debounceSerach(() => {
				let _query = query.split('-');
				if (Array.isArray(_query)) _query = _query[0];
				this.axios({
					method: 'post',
					url: '/dms/device/page',
					data: {
						deviceMId: _query,
						pageNum: 1,
						pageSize: 10,
					},
				}).then((res) => {
					if (res.code === 200) {
						this.deviceMIdList = res.data.records.map((item) => {
							item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo;
							return item;
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				});
			}, 300);
			fn();
		},
		handleCasChange(val) {
			this.searchParams.orgCode = val;
		},
		//获取故障数据
		getFaultCategory(name) {
			this.axios({
				method: 'get',
				url: '/dms/faultCategory/basicDict',
				params: { name },
			}).then((res) => {
				if (res.code === 200) {
					if (name === '故障分类') {
						this.faultCategoryList = res.data.map((item) => {
							if (item.value) return item;
						});
					} else if (name === '设备类型') {
						this.deviceTypeList = res.data.map((item) => {
							if (item.value) return item;
						});
					}
				} else {
					this.$Message.warning({
						content: res.msg,
						duration: 6,
						closable: true,
					});
				}
			});
		},
		deviceNameChange(val) {
			if (val) {
				this.searchParams.deviceType = val;
			}
		},
		handleOutRecords() {
			let params = {
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				ids: this.delIds,
				...this.searchParams,
			};
			const filName = '点检项目';
			this.axios({
				method: 'post',
				url: '/dms/dcmMaintainItem/exportItem',
				responseType: 'blob',
				data: params,
			}).then((res) => {
				fileDownload(res, filName + '.xlsx');
			});
		},
		importExcelChange(val) {
			this.importExcelState = false;
			if (val === 'success') {
				this.changeNum();
				this.$Message.success('导入成功!');
			}
		},
		//下载模板
		exportTemplate() {
			const filName = '点检项目下载模板';
			this.axios({
				method: 'get',
				url: '/dms/dcmMaintainItem/downloadTemplate',
				responseType: 'blob',
			}).then((res) => {
				fileDownload(res, filName + '.xlsx');
			});
		},
		getDeviceNameList(deviceName) {
			if (deviceName) {
				this.axios({
					method: 'get',
					url: '/dms/dcmMaintainItem/selectDeviceNames',
					params: {
						deviceName,
					},
				}).then((res) => {
					if (res.code == 200) {
						this.deviceNameList = res.data.map((val) => ({
							label: val,
							value: val,
						}));
					}
				});
			}
		},
		tabsClick(name) {
			console.log(name);
			this.status = name;
			this.delIds = '';
			this.pageNum = 1;
			this.getDatalist();
		},
		createfaultCodeShowH() {
			this.$refs.addProjectModal.show('');
		},
		//确认
		confirm(row) {
			this.confirmId = row.id;
			this.confirmFaultCodeShowF = true;
		},
		deleteConfirmOk() {
			this.confirmLoading = true;
			this.axios({
				method: 'post',
				url: '/dms/dcmMaintainItem/verifyById',
				data: {
					id: this.confirmId,
				},
			})
				.then((res) => {
					if (res.code === 200) {
						this.getDatalist();
						this.$Message.success({
							content: '确认成功！',
							duration: 2,
							closable: true,
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				})
				.finally(() => {
					this.confirmLoading = false;
					this.confirmFaultCodeShowF = false;
				});
		},
		//批量确认
		handleBatchConfirm() {
			this.confirmBatchFaultCodeShowF = true;
		},
		deleteBatchConfirmOk() {
			this.confirmBatchLoading = true;
			this.axios({
				method: 'post',
				url: '/dms/dcmMaintainItem/batchVerify',
				data: {
					ids: this.delIds,
				},
			})
				.then((res) => {
					if (res.code === 200) {
						this.getDatalist();
						this.$Message.success({
							content: '批量确认成功！',
							duration: 2,
							closable: true,
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				})
				.finally(() => {
					this.confirmBatchLoading = false;
					this.confirmBatchFaultCodeShowF = false;
				});
		},

		deleteOk() {
			this.delLoading = true;
			const obj = {
				method: 'delete',
				url: '/dms/dcmMaintainItem/delete',
				params: {},
			};
			if (this.delIds && this.delIds.length) {
				obj.url = '/dms/dcmMaintainItem/batchDelete';
				obj.params.ids = this.delIds.join(',');
			}
			if (this.delId) {
				obj.params.id = this.delId;
			}
			this.axios(obj)
				.then((res) => {
					if (res.code === 200) {
						this.getDatalist();
						this.$Message.success({
							content: '删除成功！',
							duration: 2,
							closable: true,
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				})
				.finally(() => {
					this.delLoading = false;
					this.delFaultCodeShowF = false;
				});
		},
		//批量删除
		handleBatchDelete() {
			if (!(this.delIds && this.delIds.length)) {
				this.$Message.error(`${this.$t('common.deleteItems')}`);
				return;
			}
			this.delBatchFaultCodeShowF = true;
		},
		deleteBatchOk() {
			this.delBatchLoading = true;
			this.axios({
				method: 'delete',
				url: '/dms/dcmMaintainItem/batchDelete',
				params: {
					ids: this.delIds.toString(),
				},
			})
				.then((res) => {
					if (res.code === 200) {
						this.getDatalist();
						this.$Message.success({
							content: '批量删除成功！',
							duration: 2,
							closable: true,
						});
					} else {
						this.$Message.warning({
							content: res.msg,
							duration: 6,
							closable: true,
						});
					}
				})
				.finally(() => {
					this.delBatchLoading = false;
					this.delBatchFaultCodeShowF = false;
				});
		},
		onSelectChange(selection) {
			let myArray = [];
			selection.map((item) => {
				myArray.push(item.id);
			});

			this.delIds = myArray;
			if (selection.length > 1) {
				this.allCheck = true;
			} else {
				this.allCheck = false;
			}
		},
		handleSearch() {
			// this.status = status
			this.getDatalist();
		},
		//分页
		changeNum() {
			this.pageNum = 1;
			this.getDatalist();
		},
		changePageSize(pageSize) {
			this.pageSize = pageSize;
			this.getDatalist();
		},
		changePageNum(val) {
			this.pageNum = val;
			this.getDatalist();
		},
		batchImport() {
			this.importExcelState = true;
		},
	},
};
</script>

<style lang="scss">
.tableContent {
	width: 100%;
	.table-bordered > thead > tr > th {
		border-bottom-width: 0px;
	}
}
.project {
	//background: #ffffff;
	height: calc(100vh - 150px);

	.title {
		display: flex;
		justify-content: space-between;
		font-size: 20px;
		padding: 10px;
		border-bottom: 1px solid #dddddd;

		.icon {
			display: flex;

			.creatBtnright {
				display: flex;
				align-items: center;
				font-size: 16px;

				i {
					font-size: 36px;
				}
			}
		}
	}

	.tab {
		height: calc(100% - 100px);

		.ivu-tabs-bar {
			padding-left: 30px;
		}

		.ivu-tabs-tab {
			font-size: 18px;
		}
	}
}

.addModal {
}

.batchImport {
	.import {
		display: flex;
		align-items: center;

		.selectFile {
			margin-right: 10px;
		}

		.selectFile::before {
			content: '*';
			color: red;
			padding-right: 5px;
		}
	}

	.download {
		.clickthis {
			color: #187bdb;
			text-decoration: underline;
			cursor: pointer;
		}
	}
}
</style>
